import Vue from 'vue'
import CRUD from './CRUD.vue'
import _ from 'lodash'

let components = {}
Vue.component('crud', CRUD)

// 可以传入router对象，来将页面注入到路由中（前提是模块有路由配置）
// ** 在注册模块时，先注册父级页面，再注册子页面 **
let registerModules = (router, moduleContexts) => {
  let routes = []
  _.forOwn(moduleContexts, moduleContext => {
    if (!moduleContext.prototype.key) throw Error('模块必须配置key值')
    if (components.hasOwnProperty(moduleContext.prototype.key)) throw Error('不能注册相同的模块')
    let component = Vue.extend({
      components: {CRUD},
      template: '<crud :module="module"></crud>',
      data () {
        return {
          module: moduleContext
        }
      }
    })
    components[moduleContext.prototype.key] = component
    if (router && moduleContext.prototype.routeConfig) {
      let route = _.clone(moduleContext.prototype.routeConfig)
      route.component = component
      route.__key = moduleContext.prototype.key
      if (!route.name && moduleContext.prototype.name) {
        route.name = moduleContext.prototype.name
      }
      let parentPageKey = moduleContext.prototype.routeConfig.parentPageKey
      if (parentPageKey) {
        let parentFound = false
        for (let r of routes) {
          if (r.__key === parentPageKey) {
            if (!r.children) r.children = []
            r.children.push(route)
            parentFound = true
            break
          }
        }
        if (!parentFound) throw Error(`模块[${moduleContext.prototype.key}]配置路由不正确`)
      } else {
        routes.push(route)
      }
    }
  })
  if (routes.length > 0) {
    router.addRoutes(routes)
  }
  return components
}

export {
  components,
  registerModules
}
